import {
  Component, ComponentFactory, ComponentFactoryResolver, ViewChild, ViewContainerRef,
  ViewRef
} from "@angular/core";
import {NavController} from "ionic-angular";
import {CorecontentPage} from "../corecontent/corecontent";
import {Http} from "@angular/http";
import {Storage} from "@ionic/storage"
import {ViewContainerData} from "@angular/core/src/view";

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  tabRoot = [CorecontentPage]
  constructor(public navCtrl: NavController,private cfr: ComponentFactoryResolver,private http:Http,private storage:Storage) {

    this.storage.get("contentList").then(data=>{
      if(data!=null){

        this.showData(data)
      }

    })

    // console.log(storage.get("key"))
  }

  @ViewChild('contentList', {read: ViewContainerRef}) contentList:ViewContainerRef ;

  showData(data){
    for(let i in data){
      let page:ComponentFactory<CorecontentPage> = this.cfr.resolveComponentFactory(CorecontentPage)
      let comp = this.contentList.createComponent(page)
      comp.instance.data = data[i]

    }
  }
  doRefresh(event){
    this.http.get("assets/content.json").subscribe((data)=>{
      let jsonResult = data.json();
      this.storage.get("contentList").then(data=>{
        if(data==null){
          this.storage.set("contentList",jsonResult)
        }else{
          data.push.apply(data,jsonResult);
          this.storage.set("contentList",data)
        }
      })


      this.showData(jsonResult)
      let tmp:ViewContainerData = this.contentList as ViewContainerData;


      event.complete()

    })



  }

  changeContent(content){


    console.log(content.value)
  }
}
